import base64
import os
import random
import tempfile
from datetime import datetime

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt

from app01 import models
from app01.utils.forms import OrderModelForm, FunctionForm, UserChangePasswordForm
from app01.utils.forms import UserEditModelForm
from app01.utils.imgOP import imgOP
from app01.utils.pagination import Pagination
from 智能视微 import settings


@csrf_exempt
def user_function(request):
    """用户的功能界面"""
    ID = request.session.get("info")["id"]
    queryset_recharge = models.Record.objects.filter(user=ID)
    page_object = Pagination(request, queryset_recharge)
    content = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.createHtml(),
    }
    return render(request, 'user_function.html', content)


def user_edit(request):
    """用户修改信息"""
    title = '修改用户'
    nid = request.session.get("info")['id']
    print(nid)
    row_object = models.User.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserEditModelForm(instance=row_object)
        return render(request, "user_edit.html", {'form': form, 'title': title})
    models.User.objects.filter(id=nid).update()
    form = UserEditModelForm(data=request.POST, instance=row_object)
    print(form.is_valid())
    if form.is_valid():
        # print(form.cleaned_data)
        form.save()
        return redirect('/user/function/')
    return render(request, 'user_edit.html', {"form": form, 'title': title})


def user_order_list(request):
    """订单列表"""
    ID = request.session.get("info")["id"]
    queryset_recharge = models.RechargeOrder.objects.filter(id=ID)
    page_object = Pagination(request, queryset_recharge)
    content = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.createHtml(),
    }
    return render(request, 'user_order_list.html', content)


@csrf_exempt
def user_recharge(request):
    """用户充值"""
    title = "用户充值"

    if request.method == 'GET':
        user_param = request.session.get("info")['name']
        oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))
        form = OrderModelForm(initial={"user": user_param, "oid": oid})
        content = {
            'form': form,
            'title': title
        }
        return render(request, 'user_recharge.html', content)
    user_param = request.session.get("info")['name']
    oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))
    form = OrderModelForm(data=request.POST, initial={"user": user_param, "oid": oid})

    print(form.is_valid())
    if form.is_valid():
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))
        name = request.session.get("info")["name"]
        form.instance.user = models.User.objects.filter(User_name=name).first()
        User_account = models.User.objects.filter(User_name=name).first().User_account
        form.save()
        models.User.objects.filter(User_name=name).update(User_account=User_account + form.instance.price)
        return redirect('/user/order/list/')
    content = {
        'status': False,
        'error': form.errors,
    }
    return render(request, 'user_recharge.html', content)


def image_object_to_json(image_obj):
    encoded_image = base64.b64encode(image_obj.getvalue()).decode('utf-8')
    image_json = {
        'image': encoded_image
    }
    return image_json


@csrf_exempt
def user_function_servlet(request):
    files_obj = request.FILES.getlist('file-data')
    price_obj = models.Price.objects.filter(price=1).values('price').first()
    price = len(files_obj) * price_obj['price'] if price_obj else 0
    user_obj = models.User.objects.filter(User_name=request.session.get("info")['name']).first()
    account = models.User.objects.filter(id=request.session.get("info")['name']).values('User_account').first()
    if len(files_obj) != 0 and account - price > 0:
        models.Record.objects.create(
            oid=datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999)),
            number=len(files_obj),
            price=price,
            user=user_obj
        )
        models.User.objects.filter(id=request.session.get("info")['name']).update(User_account=account - price)
    processed_files = []
    for file in files_obj:
        processed_file = imgOP(file)
        processed_files.append(processed_file)
    result = {'results': []}
    for pf in processed_files:
        image_json = image_object_to_json(pf)
        result['results'].append(image_json)

    data = {'data': result, 'msg': 'success', 'status': 200}
    return JsonResponse(data)


def user_changePassword(request):
    """用户修改密码"""
    title = '修改密码'
    nid = request.session.get("info")['id']
    row_object = models.User.objects.filter(id=nid).first()
    if request.method == "Get":
        form = UserChangePasswordForm(instance=row_object)
        content = {
            'title': title,
            'form': form
        }
        return render(request, 'user_changePassword.html', content)

    form = UserChangePasswordForm(data=request.POST, instance=row_object)
    print(form.is_valid())
    if form.is_valid():
        # print(form.cleaned_data)
        form.save()
        return redirect('/user/function/')
    return render(request, 'user_edit.html', {"form": form, 'title': title})


def user_function_result(request):
    # TODO 接受结果
    return render(request, 'user_function_result.html')
